package com.esreport.okhttp;

import okhttp3.*;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xuweiwei
 * @date 2018/12/19
 */
public class OkHttpUtils {

    public static String USER_AGENT = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";


    public static OkHttpClient buildHttpClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .followRedirects(false)
                .followSslRedirects(false)
                .cookieJar(CookieJar.NO_COOKIES)
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .build();
        return client;
    }

    public static OkHttpClient buildHttpClient(HttpProxy proxy) {
        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .followRedirects(false)
                .followSslRedirects(false)
                .cookieJar(CookieJar.NO_COOKIES)
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(2, 5L, TimeUnit.MINUTES))
                .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort())))
                .build();
        return client;
    }

    public static OkHttpClient buildHttpsClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))
                .retryOnConnectionFailure(false)
                .followRedirects(false)
                .followSslRedirects(false)
                .cookieJar(CookieJar.NO_COOKIES)
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        return client;
    }

    public static OkHttpClient buildHttpsClient(HttpProxy proxy) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))
                .retryOnConnectionFailure(false)
                .followRedirects(false)
                .followSslRedirects(false)
                .cookieJar(CookieJar.NO_COOKIES)

                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(2, 5L, TimeUnit.MINUTES))
                .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort())))
                .build();
        return client;
    }

    public static byte[] httpGetByte(OkHttpClient client, String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", USER_AGENT)
                .addHeader("Connection", "close")
                .build();
        Response response = client.newCall(request).execute();
        ResponseBody body = null;
        try {
            if (response.code() != 200 && response.code()!=206) {
                throw new HttpException("code=" + response.code());
            }
            if(response.isRedirect()){
                throw new HttpException("redirect url:"+response.header("location"));
            }
            body = response.body();
            byte[] bytes = body.bytes();
            return bytes;
        } finally {
            if(body!=null) {
                body.close();
            }
        }
    }

    public static String httpGet(OkHttpClient client, String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", USER_AGENT)
                .addHeader("Connection", "close")
                .build();
        Response response = client.newCall(request).execute();
        ResponseBody body = null;
        try {
            if (response.code() != 200 && response.code()!=206) {
                throw new HttpException("code=" + response.code());
            }
            if(response.isRedirect()){
                throw new HttpException("redirect url:"+response.header("location"));
            }
            body = response.body();
            String html = body.string();
            return html;
        } finally {
            if(body!=null) {
                body.close();
            }

        }
    }

    public static String httpPost(OkHttpClient client, String url,Map<String,String> param) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        Iterator<Map.Entry<String,String>> iterator = param.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String,String> entry = iterator.next();
            builder.add(entry.getKey(),entry.getValue());
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .addHeader("User-Agent", USER_AGENT)
                .build();
        Response response = client.newCall(request).execute();
        ResponseBody body = null;
        try {
            if (response.code() != 200 && response.code()!=206) {
                throw new HttpException("code=" + response.code());
            }
            if(response.isRedirect()){
                throw new HttpException("redirect url:"+response.header("location"));
            }
            body = response.body();
            String html = body.string();
            return html;
        } finally {
            if(body!=null) {
                body.close();
            }

        }
    }

    public static void main(String[] args) throws IOException {
        String url = "https://mp.weixin.qq.com/s?timestamp=1545358602&src=3&ver=1&signature=VzNI5qMvljphSy2MJfaY8YIAmJyrPiCE18Wa**jZ9gU3VwY6oWElrbiEv2dbBNV3u0iDjbM0YKRa**FkumaDS8v1fyESb5NgBfLVSbz9g8Mxn3ffYiWPYuRcFgCSvaNkBRcr6JWhBBAKkYy4Eo0Vd-Xa3YvxRdkBY-cIX*2xOuI=";
        OkHttpClient client = buildHttpsClient();
        String html = httpGet(client, url);
        System.out.println(html);


    }
}
